// original sampple code by GarretLab 
// from http://garretlab.web.fc2.com/arduino/lab/barometer_sensor/index.html
// templaure calcuration from https://github.com/misenso/MPL115A2-Arduino-Library/blob/master/MPL115A2.cpp
// <script src='http://pastie.org/3939144.js'></script>

// include the library code:
#include <LiquidCrystal.h>
#include <Wire.h>

const int address = 0x60;

byte rc;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


float read_coefficients(int total_bits, int fractional_bits, int zero_pad) {
  unsigned char msb, lsb;
  
  msb = Wire.read();
  lsb = Wire.read();
  
  return ((float) ((msb << 8) + lsb) / ((long)1 << 16 - total_bits + fractional_bits + zero_pad));
}

unsigned int read_adc() {
  unsigned char msb, lsb;
  msb = Wire.read();
  lsb = Wire.read();
  
  return (((unsigned int)msb << 8) + lsb) >> 6;
}  

float a0, b1, b2, c12, c11, c22;

void setup () {
  
  startUpSensor();
  lcd.begin(16,2);

  lcd.setCursor(0,0);
  lcd.print("initializing..");

  pinMode(8, OUTPUT);

  Wire.begin();
  // Serial.begin(9600);
  
  Wire.beginTransmission(address);
  Wire.write(0x04);        // Read coefficient data
  rc=Wire.endTransmission();
  
  Wire.requestFrom(address, 12);  // Request 12 bytes
  if (Wire.available()) {
    a0 = read_coefficients(16, 3, 0);
    b1 = read_coefficients(16, 13, 0);
    b2 = read_coefficients(16, 14, 0);
    c12 = read_coefficients(14, 13, 9);
    c11 = read_coefficients(11, 10, 11);
    c22 = read_coefficients(11, 10, 15);
  }
  // Serial.print("setup() rc is ");
  // Serial.println(rc);


}

void shutDownSensor() {
  digitalWrite(8, LOW);
}
void startUpSensor() {
  digitalWrite(8, HIGH);
}


void loop () {
  float Pha;
  float tempv;
  
  lcd.clear();
  lcd.setCursor(0, 0);
  Wire.beginTransmission(address);
  Wire.write(0x12);      // Start both conversions(Pressure and Temperature)
  Wire.write(0x01);
  Wire.endTransmission();

  delay(5);

  Wire.beginTransmission(address);
  Wire.write((uint8_t)0x00);  // Read pressure and temperature
  rc=Wire.endTransmission();

  Wire.requestFrom(address, 4); // Request 4 bytes

  if(Wire.available()) {
    unsigned int Padc = read_adc();
    unsigned int Tadc = read_adc();
  
    float Pcomp = a0 + (b1 + c11 * Padc + c12 * Tadc) * Padc + (b2 + c22 * Tadc) * Tadc;
    tempv=25 + (Tadc - 498.0) / -5.35;
    Pha = Pcomp * 650 / 1023 + 500;
    // Serial.println(Pha);
  }
  lcd.print("Temp :");
  lcd.print(tempv);
  lcd.setCursor(0,1);
  lcd.print("Baro :");
  lcd.print(Pha);
   
  // Serial.print("loop () rc is ");
  // Serial.println(rc);

  shutDownSensor();
  delay(5000);
  startUpSensor();
  
}
